import flask
from flask import render_template, redirect, url_for

from . import sqlhelper
from .server_helper import *

__all__ = [
    'bp'
]

bp = flask.Blueprint('user', __name__)


@bp.route('/user/regist', methods=['GET', 'POST'])
def user_regist():
    if request.method == 'GET':
        tpl = "user.html"
        return render_template(tpl)

    if request.method == 'POST':
        req = parser_req()
        un = req.username
        pw = req.password

        n = sqlhelper.insert_one("insert into t_user(name,nickname,passwd) value(%s,%s,%s)", (un, un, pw))
        if n > 0:
            return return_ok()
        return return_fail()


@bp.route('/user/login', methods=['GET', 'POST'])
def user_login():
    if request.method == 'GET':
        tpl = "user.html"
        return render_template(tpl)

    if request.method == 'POST':
        req = parser_req()
        req.pprint('json')
        un = req.username
        pw = req.password

        n = sqlhelper.select_one("select uid from t_user where name=%s and passwd=%s limit 1", (un, pw))
        if n:
            return redirect(url_for('dyb.index'))
        return return_fail()


@bp.route('/user/logout', methods=['POST'])
def user_logout():
    return {
        "state": 200,
        "data": 'success'
    }


@bp.route('/user/<uid>', methods=['GET'])
def get_user_info(uid: str):
    return {
        "state": 200,
        "data": {
            "roles": ['admin'],
            "introduction": 'I am a super administrator',
            "avatar": 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            "name": 'Super Admin'
        },
    }
